
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

#define BUF_SIZE 10
void add_count(FILE *);

unsigned long count;
int size = sizeof(count);

void main(){
	FILE * file = fopen("counter.dat","wb");
	if(file == NULL){
		perror("cannot open file");
		return;
	}

	pid_t pid[1];

	pid[0] = fork();

	if(pid[0] == -1){
		printf("fork error\n");
		return;
	}
	if(pid[0] ==0){
		printf("child process\n");
		while(1){
			add_count(file);
			if(count % 10000==0){
				printf("child, count=%ld\n", count);
			}
		}
	}else{
		printf("parent process\n");
		while(1){
			add_count(file);
			if(count % 10000==0){
				printf("parent, count=%ld\n", count);
			}
		}
	}

	wait(0);
}

// size_t fread (void *ptr, size_t size, size_t nmemb, FILE *stream);
// size_t fwrite(const void *ptr, size_t size, size_t nmemb,FILE *stream);
void add_count(FILE * file){
	int sz = fread(&count,size,1,file);
	// printf("read size=%d\n",sz);
	count++;
	fseek(file,0,SEEK_SET);
	fwrite(&count,size,1,file);
}